const socketIo = require('socket.io')

const { attachToFireLink } = require('../fireLink');
const onGetHubInfo = require('./onGetHubInfo')
const onSendData = require('./onSendData');

let io;

function ioStart (server) {
  console.log('====================================')
  io = socketIo(
    server,
    {
      cors: {
        origin: process.env.CORS_ORIGIN,
        methods: ['GET', 'POST'],
      },
    }
  )

  attachToFireLink(io)
  
  io.on('connection', (client) => {
    console.log('==== ioOnConnection START', client.id)
    client.on('getHubInfo', onGetHubInfo)
    client.on('sendData', onSendData)
  })
}

function emitToAll (event, value) {
  io.emit(event, value)
}

module.exports = {
  emitToAll,
  ioStart,
}
